//
//  RequestManager.m
//  MyPizzaMobile
//
//  Created by Stanislav on 2/15/13.
//  Copyright (c) 2013 Stanislav. All rights reserved.
//

#import "RequestManager.h"

@interface RequestManager()
{
    JSONDecoder * decoder;
    NSURLConnection *urlConnection;
}
@end

@implementation RequestManager
@synthesize orderSupplements, orderPizzas;
static RequestManager* _instance = nil;

- (id)init
{
    self = [super init];
    if(self)
    {
        decoder = [[JSONDecoder alloc]init];
        self.orderSupplements = [[NSMutableDictionary alloc]init];
        self.orderPizzas = [[NSMutableDictionary alloc]init];
    }
    return self;
    
}

+(RequestManager*)requestManagerInstance
{
	@synchronized([RequestManager class])
	{
		if (!_instance)
			_instance = [[self alloc] init];
        
		return _instance;
	}
    
	return nil;
}

- (BOOL) orderPizza
{
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    NSString * userId = [defaults objectForKey:@"id"];
    NSString *password = [defaults objectForKey:@"password"];
    NSString * size = [self.orderPizzas objectForKey:@"size"];
    NSString * name = @"custom";
    NSString * price = [self.orderPizzas objectForKey:@"totalPrice"];
    NSString * orderAddress = [self.orderPizzas objectForKey:@"orderAddress"];

    NSString *post = [[NSString alloc]initWithFormat:@"operation=setOrder&userId=%@&name=%@&password=%@&size=%@&price=%@&orderAddress=%@&json=%@",userId,name, password,size,price,orderAddress,[self.orderSupplements JSONString]];
    NSDictionary* newDict = [self makeRequestWithStringData:post];
    NSString *newId = [newDict objectForKey:@"result"];
    if(newId)
    {
//        UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Success"
//                                                          message:@"You successfull order a pizza!"
//                                                         delegate:nil
//                                                cancelButtonTitle:@"OK"
//                                                otherButtonTitles:nil];
//        message.tag = 1;
//        [message show];
        return YES;
    }
    return NO;
}



- (BOOL) sendRegistrationWithDict:(NSDictionary *) dict
{
    NSString *post = [[[[[[[[[@"operation=register&username=" stringByAppendingString:
                              [self escape:[dict objectForKey:@"username"]]]
                           stringByAppendingString:@"&password="] stringByAppendingString:
                                [self escape:[dict objectForKey:@"password"]]]
                         stringByAppendingString:@"&address="] stringByAppendingString:
                                [self escape:[dict objectForKey:@"address"]]]
                        stringByAppendingString:@"&phone="] stringByAppendingString:
                                [self escape:[dict objectForKey:@"phone"]]]
                       stringByAppendingString:@"&ordersAddress="]stringByAppendingString:
                                [self escape:[dict objectForKey:@"ordersAddress"]]];
    NSMutableDictionary* dictionary = [[NSMutableDictionary alloc] initWithDictionary:dict];
    NSDictionary* newDict = [self makeRequestWithStringData:post];
    if(newDict)
    {
        NSString *newId = [newDict objectForKey:@"result"];
        [dictionary setObject:[[NSString alloc] initWithFormat:@"%@",newId] forKey:@"id"];
        [self saveUserProfileDataFromDict:dictionary];
        return YES;
    }
    else{
        return NO;
    }
}

- (BOOL) sendLoginWithDict:(NSDictionary *) dict
{
    NSString *post = [[[@"operation=login&username=" stringByAppendingString:
                        [self escape:[dict objectForKey:@"username"]]]
                           stringByAppendingString:@"&password="] stringByAppendingString:
                        [self escape:[dict objectForKey:@"password"]]];
    
    NSDictionary *usrDict = [self makeRequestWithStringData:post];
    if(usrDict)
    {
        NSMutableDictionary *newUserProperties = [[NSMutableDictionary alloc] initWithDictionary:usrDict];
        NSString *result = [usrDict objectForKey:@"id"];
        [newUserProperties setObject:[[NSString alloc] initWithFormat:@"%@",result] forKey:@"id"];
        [self saveUserProfileDataFromDict:newUserProperties];

        return YES;
    }
    else
    {
//        UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Error"
//                                                          message:@"Wrong username or password!"
//                                                         delegate:nil
//                                                cancelButtonTitle:@"OK"
//                                                otherButtonTitles:nil];
//        [message show];
       return NO;
    }
}

- (BOOL) updateUserFromDictionary:(NSDictionary*)dict
{
    NSString *post = [[[[[[[[[[[@"operation=updateUser&username=" stringByAppendingString:
                              [self escape:[dict objectForKey:@"username"]]]
                             stringByAppendingString:@"&password="] stringByAppendingString:
                            [self escape:[dict objectForKey:@"password"]]]
                           stringByAppendingString:@"&address="] stringByAppendingString:
                          [self escape:[dict objectForKey:@"address"]]]
                         stringByAppendingString:@"&phone="] stringByAppendingString:
                        [self escape:[dict objectForKey:@"phone"]]]
                       stringByAppendingString:@"&ordersAddress="]stringByAppendingString:
                      [self escape:[dict objectForKey:@"ordersAddress"]]]
                    stringByAppendingString:@"&id="]stringByAppendingString:
                    [dict objectForKey:@"id"]];
    
    NSDictionary*resultDict = [self makeRequestWithStringData:post];
    if(resultDict)
    {
        int result = [[resultDict objectForKey:@"result"] integerValue];
        NSMutableDictionary* dictionary = [[NSMutableDictionary alloc] initWithDictionary:dict];
        [dictionary setObject:[[NSString alloc] initWithFormat:@"%d",result] forKey:@"id"];
        [self saveUserProfileDataFromDict:dictionary];
        return YES;
    }
    else
    {
        return NO;
    }
}

- (NSDictionary*) getAllPizzaSupplements
{
    NSString *post = [@"operation=getAllSupplements" stringByAppendingString:[self getUserIdAndPasswordForRequest]];
    
  return [self makeRequestWithStringData:post];
}

- (void) getPizzaSupplementsById:(NSInteger) pizzaId
{
    NSString *pizzaIdentity = [[NSString alloc] initWithFormat:@"%d",pizzaId];
    NSString *post = [[@"operation=getPizzaSupplementsById&id=" stringByAppendingString:pizzaIdentity] stringByAppendingString:[self getUserIdAndPasswordForRequest]];
    [self makeRequestWithStringData:post];
    
}

- (NSDictionary *) makeRequestWithStringData:(NSString*)post
{
    NSMutableURLRequest  * request;
    
    NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    
    request = [[NSMutableURLRequest alloc]init];
    [request setURL:[NSURL URLWithString:[Constants getServerURL]]];
    [request setHTTPMethod: @"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];
    NSURLResponse *response;
    NSError *err;
    NSData * responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    NSDictionary *responseDict = [decoder objectWithData:responseData error:&err];
    
    NSString *requestResult = [responseDict objectForKey:@"error"];
    if(requestResult == nil)
    {
        int result = [responseDict count];
        if(result >0)
        {
            return responseDict;
        }
        else
        {
            UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Error"
                                                              message:@"Unable to get data from server!"
                                                             delegate:nil
                                                    cancelButtonTitle:@"OK"
                                                    otherButtonTitles:nil];
            [message show];
            return nil;
        }

    }
    else
    {
        UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Error"
                                                          message:requestResult
                                                         delegate:nil
                                                cancelButtonTitle:@"OK"
                                                otherButtonTitles:nil];
        [message show];
    }
    return nil;
}

- (void) saveUserProfileDataFromDict:(NSDictionary *)dict
{
    NSString* userId = [dict objectForKey:@"id"];
    NSString* username = [self escape:[dict objectForKey:@"username"]];
    NSString* password = [self escape:[dict objectForKey:@"password"]];
    NSString* address = [self escape:[dict objectForKey:@"address"]];
    NSString* phone = [self escape:[dict objectForKey:@"phone"]];
    NSString* ordersAddress = [self escape:[dict objectForKey:@"ordersAddress"]];
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:userId forKey:@"id"];
    [userDefaults setObject:username forKey:@"username"];
    [userDefaults setObject:password forKey:@"password"];
    [userDefaults setObject:address forKey:@"address"];
    [userDefaults setObject:phone forKey:@"phone"];
    [ordersAddress length]?[userDefaults setObject:ordersAddress forKey:@"ordersAddress"]:nil;
    
    [userDefaults setBool:YES forKey:@"registeredUser"];
    
    [userDefaults synchronize];
}

- (NSString*) escape:(NSString *)stringToEscape
{
    NSString* escapedUrlString = [stringToEscape stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
    return escapedUrlString;
}
- (NSString*) unescape:(NSString *)string
{
    NSString* escapedUrlString = [string stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
    return escapedUrlString;
}
- (NSString *) getUserIdAndPasswordForRequest
{
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    NSString *userId = [defaults objectForKey:@"id"];
    NSString *password = [defaults objectForKey:@"password"];
    NSString * result = [[[@"&userId=" stringByAppendingString:userId]
stringByAppendingString:@"&password="] stringByAppendingString:password];
    return result;
}

- (double) getShippingPrice
{
    return 5.0f;
}
@end
